43.3.7 Auto-configured JSON Tests
43.3.7 自动配置的JSON测试
你可以使用@JsonTest测试对象JSON序列化和反序列化是否工作正常。该注解将自动配置支持JSON映射器的可用库。可以是下列库里的一种:
- Jackson ObjectMapper,任何- @JsonComponentbean,任何Jackson- 模块
- Gson
- Jsonb
使用@AutoConfigureJsonTesters可以配置auto-configuration的元素。
Spring Boot提供基于AssertJ的帮助类(helpers),可用来配合JSONassert和JsonPath库检测JSON是否和期望的一样。JacksonTester、GsonTester、JsonbTester和BasicJsonTester分别用于Jackson、Gson、Jsonb、Strings。当使用@JsonTest时,你可以在测试类中@Autowired任何helper字段。下面的例子展示了一个用于Jackson的测试类:
import org.junit.*;
import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.boot.test.autoconfigure.json.*;
import org.springframework.boot.test.context.*;
import org.springframework.boot.test.json.*;
import org.springframework.test.context.junit4.*;
import static org.assertj.core.api.Assertions.*;
@RunWith(SpringRunner.class)
@JsonTest
public class MyJsonTests {
    @Autowired
    private JacksonTester<VehicleDetails> json;
    @Test
    public void testSerialize() throws Exception {
        VehicleDetails details = new VehicleDetails("Honda", "Civic");
        // Assert against a `.json` file in the same package as the test
        assertThat(this.json.write(details)).isEqualToJson("expected.json");
        // Or use JSON path based assertions
        assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");
        assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make")
                .isEqualTo("Honda");
    }
    @Test
    public void testDeserialize() throws Exception {
        String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
        assertThat(this.json.parse(content))
                .isEqualTo(new VehicleDetails("Ford", "Focus"));
        assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford");
    }
}
注 JSON帮助类可用于标准单元测试类,如果没有使用@JsonTest,你需要在@Before方法中调用帮助类的initFields方法。
在附录中可以查看@JsonTest开启的自动配置列表。